package com.example.hw_demo.interceptor;

import com.example.hw_demo.util.Result;
import com.example.hw_demo.util.TokenUtil;
import com.google.gson.Gson;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 处理拦截的请求
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tokenString = request.getHeader("token");//从请求中获取token字符串
        String uri = request.getRequestURI();//获取url:user/login

        //返回token拦截信息
        response.setCharacterEncoding("utf-8");
        response.setContentType("json/application");
        //判断
        if(uri.equals("/user/login")||request.getMethod().equals("OPTIONS")){
            return  true;
        }else{
            //token认证
            if(tokenString==null||tokenString.equals("")){
                //无token，重新登录
                //将返回信息转换成json字符串响应
                response.getWriter().println(new Gson().toJson(new Result(500,"无token,请重新登录",null)));
                return  false;
            }
            //token认证
            if(!new TokenUtil().verifyToken(tokenString)){
                //解析失败
                //将返回信息转换成json字符串响应
                response.getWriter().println(new Gson().toJson(new Result(500,"token认证失败,请重新登录",null)));
                return  false;
            }else{
                //解析成功
                return  true;
            }
            //token过期
        }
    }
}
